package com.cx.common;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.google.common.collect.Lists;

import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;
import java.io.OutputStream;
import java.util.List;

public class EasyExcelUtils {

    /**
     * 导出
     *
     * @param data     数据
     * @param response
     * @param fileName 文件名
     * @param voClass
     * @throws Exception
     */
    public static void export(List data, HttpServletResponse response, String fileName, Class voClass) throws Exception {
        OutputStream out = null;
        ExcelWriter writer = null;
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
            List lt = Lists.partition(data, 50000);
            for (int i = 0; i < lt.size(); i++) {
                Sheet sheet = new Sheet((i + 1), 0, voClass, "sheet" + (i + 1), null);
                writer.write((List<? extends BaseRowModel>) lt.get(i), sheet);
            }
            data.clear();
        } catch (Exception e) {
            throw new SerialException("文档下载失败" + e.getMessage());
        } finally {
            out.flush();
            writer.finish();
            out.close();
        }
    }
}
